package com.byedu.course.controller;


import com.byedu.course.util.ControllerUtil;
import com.byedu.course.util.UserExportExcelUtil;
import com.byedu.domain.focus.*;
import com.byedu.domain.focus.vo.enumvos.FocusDepartmentTypeVO;
import com.byedu.domain.focus.vo.enumvos.FocusExecuteTypeVO;
import com.byedu.domain.focus.vo.enumvos.FocusdepaTypeVO;
import com.byedu.domain.focus.vo.enumvos.FocusdepaTypeEnum;
import com.byedu.domain.focus.vo.FocusKpiVO;
import com.byedu.domain.focus.vo.FocusLogVO;
import com.byedu.domain.focus.vo.FocusUserVO;
import com.byedu.focus.*;
import com.byedu.util.CommonUtil;
import com.byedu.util.page.PageInfo;
import com.byedu.util.yunpian.util.StringUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Luo on 2017-06-28.
 */
@Controller
@RequestMapping("/user")
public class AdminUserController {

    @Autowired
    private FocusProduceService focusProduceService;
    @Autowired
    private FocusUserService focusUserService;
    @Autowired
    private FocusKpiService focusKpiService;
    @Autowired
    private FocusProjectService focusProjectService;
    @Autowired
    private FocusLogService focusLogService;


    @RequestMapping("/index")
    public String index(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String m = request.getParameter("m");
        FocusUserVO adminUser = ControllerUtil.checkuser(request, response);

        if(StringUtils.isEmpty(m)){
            m = "user";
        }

        Calendar a=Calendar.getInstance();
        request.setAttribute("m", m);
        List<FocusKpiVO> kpiList= null;
        FocusKpiDO focusKpiDO = null;
        if(adminUser.getPermission().getCode() == FocusdepaTypeEnum.BOSS.getCode()){
            kpiList  = focusKpiService.getFocusKpiDOByFocusKpiDO(null, a.get(Calendar.YEAR)+"_1");
        }else {
            kpiList = focusKpiService.getFocusKpiDOByFocusKpiDO(adminUser.getId(), a.get(Calendar.YEAR)+"_1");
        }
        focusKpiDO = focusKpiService.getkpiListSum(kpiList);

        request.setAttribute("firstsnum",focusKpiDO.getKipnum());
        if(adminUser.getPermission().getCode() == FocusdepaTypeEnum.BOSS.getCode()){
            kpiList  = focusKpiService.getFocusKpiDOByFocusKpiDO(null, a.get(Calendar.YEAR)+"_2");
        }else {
            kpiList = focusKpiService.getFocusKpiDOByFocusKpiDO(adminUser.getId(), a.get(Calendar.YEAR)+"_2");
        }
        focusKpiDO = focusKpiService.getkpiListSum(kpiList);
        request.setAttribute("secondnum",focusKpiDO.getKipnum());
        if(adminUser.getPermission().getCode() == FocusdepaTypeEnum.BOSS.getCode()){
            kpiList  = focusKpiService.getFocusKpiDOByFocusKpiDO(null, a.get(Calendar.YEAR)+"_3");
        }else {
            kpiList = focusKpiService.getFocusKpiDOByFocusKpiDO(adminUser.getId(), a.get(Calendar.YEAR)+"_3");
        }
        focusKpiDO = focusKpiService.getkpiListSum(kpiList);
        request.setAttribute("thridnum",focusKpiDO.getKipnum());
        if(adminUser.getPermission().getCode() == FocusdepaTypeEnum.BOSS.getCode()){
            kpiList  = focusKpiService.getFocusKpiDOByFocusKpiDO(null, a.get(Calendar.YEAR)+"_4");
        }else {
            kpiList = focusKpiService.getFocusKpiDOByFocusKpiDO(adminUser.getId(), a.get(Calendar.YEAR)+"_4");
        }
        focusKpiDO = focusKpiService.getkpiListSum(kpiList);
        request.setAttribute("fourthnum",focusKpiDO.getKipnum());
        return "index";
    }

    @RequestMapping("/manage")
    public String user(HttpServletResponse resp, HttpServletRequest req
     ,@RequestParam(value = "page", required = false) String pageStr) throws IOException {
        int pageInt = CommonUtil.StringToPageInt(pageStr);

        String m = req.getParameter("m");
        FocusUserVO adminUser = ControllerUtil.checkuser(req,resp);

        List<FocusdepaTypeVO> fsTypeList = focusUserService.listFocusdepaTypeVO();
        req.setAttribute("fsTypeList",fsTypeList);
        List<FocusExecuteTypeVO> executeList = focusUserService.listFocusexecuteTypeVO();
        req.setAttribute("executeList",executeList);
        List<FocusDepartmentTypeVO> departList = focusUserService.listFocusDepartmentTypeVO();
        req.setAttribute("departList",departList);
        if(m.equals("list")){
            Page page = PageHelper.startPage(pageInt, 5);
            FocusdepaTypeVO focusdepaTypeVO = new FocusdepaTypeVO();
            focusdepaTypeVO.setCode(0);
            focusdepaTypeVO.setValue("全部");
            fsTypeList.add(focusdepaTypeVO);
            List<FocusUserVO> userList =null;
           String key = req.getParameter("key");
            int  permission = CommonUtil.StringToInt(req.getParameter("permission"));
            if(StringUtil.isNullOrEmpty(key) && permission == 0){
                userList    = focusUserService.getFocusUserList();
            }else if(permission != 0){
                userList    = focusUserService.getFocusUserListbypermissionpr( permission);
            }else{
                String name = new String(key.getBytes("iso8859-1"),"utf-8");
//                System.out.print("key--"+name);
                userList    = focusUserService.getFocusUserListbyName(name);
            }
            PageInfo pi=new PageInfo(req.getContextPath()+"/user/manage?m=list&page=",page.getTotal(),page.getPageNum(),5);
            req.setAttribute("PageInfo", pi);
            req.setAttribute("userList",userList);
            req.setAttribute("downexcel", UserExportExcelUtil.userExcelexpot(userList,adminUser));
            return ControllerUtil.toHtml(adminUser,"user/userList",req,resp);
        }
        if(m.equals("add")){
            return ControllerUtil.toHtml(adminUser,"user/adduser",req,resp);
        }
        if(m.equals("edit")){
            String id = req.getParameter("id");
            FocusUserVO userEntity = focusUserService .getFocusUserbyUserId(id);
            req.setAttribute("userEntity",userEntity);
            return ControllerUtil.toHtml(adminUser,"user/adduser",req,resp);
        }
        return ControllerUtil.toHtml(adminUser,"user/userList",req,resp);
    }


    @ResponseBody
    @RequestMapping("/deluser")
    public BaReSult deluser(HttpServletResponse resp, HttpServletRequest req,
                            FocusUserDO focusUserDO
    ) throws IOException {
//        return new BaReSult("操作失败，请联系管理员");
        Integer retInt = 0;
        FocusUserVO adminUser = ControllerUtil.checkuser(req,resp);
        if(adminUser.getPermission().getCode()== FocusdepaTypeEnum.BOSS.getCode()){
            focusLogService.addFocusLogDO(new FocusLogDO(adminUser.getId(),"删除员工",focusUserDO.toString()));
            retInt= focusUserService.delFocusUser(focusUserDO);
        }else {
            return new BaReSult("权限不够");
        }
        if(retInt>0){
            return new BaReSult(true);
        }else{
            return new BaReSult("请联系管理员");
        }
    }
    @ResponseBody
    @RequestMapping("/adduser")
    public BaReSult adduser(HttpServletResponse resp, HttpServletRequest req,
                              FocusUserDO focusUserDO
    ) throws IOException {
        String m = req.getParameter("m");
        Integer retInt = 0;
        FocusUserVO adminUser = ControllerUtil.checkuser(req,resp);
        if(adminUser.getPermission().getCode() == FocusdepaTypeEnum.BOSS.getCode()){
            if(m.equals("doadd")) {
                focusLogService.addFocusLogDO(new FocusLogDO(adminUser.getId(),"添加员工",focusUserDO.toString()));
                retInt = focusUserService.addFocusUser(focusUserDO);
            } else {
                focusLogService.addFocusLogDO(new FocusLogDO(adminUser.getId(),"更新员工",focusUserDO.toString()));
                retInt = focusUserService.updateFocusUserUserId(focusUserDO);
            }
        }else {
                if (m.equals("doedit"))  {
                    focusLogService.addFocusLogDO(new FocusLogDO(adminUser.getId(),"更新员工",focusUserDO.toString()));
//                    retInt = focusUserService.updateFocusUserUserId(focusUserDO);
                    if(adminUser.getId().equals(focusUserDO.getId())){
                        retInt =   ControllerUtil.saveuser(req, focusProjectService, focusUserService, new FocusUserVO(focusUserDO));
                    }else{
                        retInt = focusUserService.updateFocusUserUserId(focusUserDO);
                    }
                }
        }

        if(retInt > 0){
            return new BaReSult(true);
        }else{
            return new BaReSult("请联系管理员");
        }
    }


    @RequestMapping("/login")
    public String login(HttpServletRequest request){

        //获取用户登陆的用户名密码
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/submitlogin", method = RequestMethod.POST)
    public BaReSult submitlogin(HttpServletResponse resp, HttpServletRequest req,
//                              String username,String password
                               FocusUserDO focusUserDO
    ){
        //如果传输数据是 @RequestBody接收的是一个Json对象的字符串 如果用表单提交直接写参数，或者对象就行
        //数据库查询用户密码是否正确，返回查询结果

        FocusUserVO checkUser = focusUserService.getFocusUser(focusUserDO);
        System.out.println(checkUser);

        //判断用户是否存在
        if(checkUser != null){
            //将用户放置于Session中，客户端全局读取
            try {
                req.getSession().setAttribute("user",checkUser);
                Cookie autoCookie = new Cookie("user", URLEncoder.encode(checkUser.getUsername(), "UTF-8")+"-"+URLEncoder.encode(checkUser.getPassword(), "UTF-8"));
                autoCookie.setPath(req.getContextPath()+"/");
                autoCookie.setMaxAge(60*60*24*30);
                resp.addCookie(autoCookie);

                focusLogService.addFocusLogDO(new FocusLogDO(checkUser.getId(),ControllerUtil.getRemoteHost(req)+"登陆系统",checkUser.toString()));
                return new BaReSult(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new BaReSult("账号密码错误，请联系管理员");
    }

    @RequestMapping("/usersetting")
    public String usersetting(HttpServletResponse resp, HttpServletRequest req
    ) throws IOException {
        String m = req.getParameter("m");
        FocusNoticeDO focusNoticeDO = focusUserService.getFocusNotice();
        req.getSession().setAttribute("userEntity",focusNoticeDO);
        if( "doedit".equals(m) ){

        }

        return "user/adduserSetting";
    }
    @ResponseBody
    @RequestMapping("/addusersetting")
    public BaReSult addusersetting(HttpServletResponse resp, HttpServletRequest req,
                                   FocusNoticeDO FocusNoticeDO
    ) throws IOException {
        String m = req.getParameter("m");
        int dd = 0;
        FocusUserVO adminUser = ControllerUtil.checkuser(req,resp);
        if(adminUser.getPermission().getCode()== FocusdepaTypeEnum.BOSS.getCode()) {
             dd = focusUserService.updateFocusNoticeDO(FocusNoticeDO);


        }
        if(dd>0) {
            focusLogService.addFocusLogDO(new FocusLogDO(adminUser.getId(), "修改通知项", FocusNoticeDO.toString()));
            return new BaReSult(true);
        }else{
            return new BaReSult("更新错误");
        }
    }
    @RequestMapping("/userlog")
    public String userlog(HttpServletResponse resp, HttpServletRequest req
    ) throws IOException {
        String userid = req.getParameter("userid");
        List<FocusLogVO> logList = null;
        FocusUserVO adminUser = ControllerUtil.checkuser(req, resp);
        List<FocusUserVO> userList = focusUserService.getFocusUserList();
        req.setAttribute("userList", userList);
        if(adminUser.getPermission().getCode() == FocusdepaTypeEnum.BOSS.getCode()){
            if(StringUtil.isNullOrEmpty(userid)) {
                logList = focusLogService.getFocusLogDOList();
            }else {
                logList = focusLogService.getFocusLogDOByUserId(userid);
            }
        }else{
            logList = focusLogService.getFocusLogDOByUserId(adminUser.getId());
        }
        req.setAttribute("logList",logList);
        return "user/userLogList";
    }

    @RequestMapping("/quit")
    public String quit(HttpServletRequest request,HttpServletResponse response) throws IOException {

        //将用户放置于Session中，客户端全局读取
        try {
            request.getSession().removeAttribute("user");
            Cookie autoCookie = new Cookie("user", null+"-"+null);
            autoCookie.setPath(request.getContextPath()+"/");
            response.addCookie(autoCookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  "login";
    }
}
